<?php
// 数据库配置
define('DB_HOST', 'localhost');
define('DB_NAME', 'music_db');
define('DB_USER', '73327382');
define('DB_PASS', '73327382');

// 创建数据库连接
try {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // 确保表结构存在
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS songs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            title VARCHAR(255) NOT NULL,
            artist VARCHAR(255) NOT NULL,
            mp3_url VARCHAR(255) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ");
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// 获取GET参数
$title = $_GET['name'] ?? '';
$artist = $_GET['artist'] ?? '';
$mp3_url = $_GET['url'] ?? '';
$album = $_GET['album'] ?? '';
// 验证必填字段
if (empty($title) || empty($artist) || empty($mp3_url) || empty($album)) {
    header('Content-Type: application/json');
    echo json_encode([
        'status' => 'error',
        'message' => '缺少必填参数: name, artist, album 或 url'
    ]);
    exit;
}

try {
    // 添加新歌曲
	$stmt = $pdo->prepare("INSERT INTO songs (title, artist, album, mp3_url) VALUES (?, ?, ?, ?)");
	$stmt->execute([$title, $artist, $album, $mp3_url]);
    
    // 获取插入的ID
    $id = $pdo->lastInsertId();
    
    // 返回成功响应
    header('Content-Type: application/json');
    echo json_encode([
        'status' => 'success',
        'message' => '歌曲添加成功',
        'data' => [
            'id' => $id,
            'title' => $title,
            'artist' => $artist,
			'album' => $album,
            'mp3_url' => $mp3_url
        ]
    ]);
    
} catch (PDOException $e) {
    // 返回错误响应
    header('Content-Type: application/json');
    echo json_encode([
        'status' => 'error',
        'message' => '数据库错误: ' . $e->getMessage()
    ]);
}